package jwei.apps.indextank.service;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class LocationProvider {

    private Context c;

    private Criteria criteria;

    private LocationManager locationManager;

    public LocationProvider(Context c) {
        this.c = c;
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        // Get a reference to the LocationManager.
        locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
    }

    /**
     * Primary method for getting Location after instantiating the
     * LocationProvider class. This method retrieves your last known location
     * and then requests an update.
     * 
     * @return
     */
    public Location getLocationAndUpdate() {
        String provider = locationManager.getBestProvider(criteria, true);

        // get cached location
        Location location = locationManager.getLastKnownLocation(provider);

        // tell location manager to update again
        locationManager.requestLocationUpdates(provider, 60000, 100, locationListener);

        return location;
    }

    /**
     * Should be called after location found for user battery power
     * conservation.
     */
    private void removeListener() {
        locationManager.removeUpdates(locationListener);
    }

    private final LocationListener locationListener = new LocationListener() {

        public void onLocationChanged(Location location) {
            System.out.println("LOCATION LISTENER UPDATED USER LOCATION");
            removeListener();
        }

        public void onProviderDisabled(String provider) {
            Toast t = Toast.makeText(c, "GPS provider lost - search results may not reflect your real location.",
                    Toast.LENGTH_SHORT);
            t.show();
        }

        public void onProviderEnabled(String provider) {
            Toast t = Toast.makeText(c, "GPS provider found - searching for your location!", Toast.LENGTH_SHORT);
            t.show();
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

    };

}
